/* $Id: ContestUserScoreModel.java 129 2011-08-26 05:27:43Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.models.scores;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;

import alt.djudge.frontend.server.Deployment;
import alt.djudge.frontend.server.datatypes.scores.ContestUserScoreEntry;
import alt.djudge.frontend.server.models.AbstractBigtableModelCore;
import alt.djudge.frontend.server.models.AbstractDBModelCore;
import alt.djudge.frontend.server.models.CoreInterface;


public class ContestUserScoreModel
{
	private static CoreInterface<ContestUserScoreEntry> core = Deployment.isGAE() ?  
		new AbstractBigtableModelCore<ContestUserScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.desc("uniqueAcceptedCount");
			}
			
			@Override
			protected Class<ContestUserScoreEntry> getEntryClass()
			{
				return ContestUserScoreEntry.class;
			}
		}
	:
		new AbstractDBModelCore<ContestUserScoreEntry>()
		{
			@Override
			protected Order getOrdering()
			{
				return Order.desc("uniqueAcceptedCount");
			}
			
			@Override
			protected Class<ContestUserScoreEntry> getEntryClass()
			{
				return ContestUserScoreEntry.class;
			}
		};		
	
	public static ContestUserScoreEntry getContestUserEntry(Long contestId, Long userId)
	{
		ContestUserScoreEntry entry = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("contestId", contestId);
		map.put("userId", userId);
		List<ContestUserScoreEntry> list = core.getEntries(map);
		if (list.size() > 0)
		{
			entry = list.get(0);
		}
		else
		{
			entry = new ContestUserScoreEntry(contestId, userId);
			entry.makePersistent();
		}
		return entry;
	}
	
	// TODO: cache me
	public static List<ContestUserScoreEntry> getContestEntries(Long contestId)
	{
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("contestId", contestId);
		List<ContestUserScoreEntry> list = core.getEntries(map);
		return list;
	}
	
	public static List<ContestUserScoreEntry> getAllEntries()
	{
		List<ContestUserScoreEntry> list = core.getAllEntries();
		return list;
	}
	
	public static void deleteAllEntries()
	{
		core.deleteAllEntries();
	}
}
